
#ifndef ROARLANG_H
#define ROARLANG_H
#include <stddef.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
typedef size_t FSM_PTR;
typedef size_t STATE_PTR;
typedef size_t MSG_PTR;
typedef size_t MSGHDLR_PTR;
typedef size_t DequeNode_PTR;
typedef size_t STR_PTR;
typedef size_t NOBJ_PTR;
typedef struct OB_FSM OB_FSM;
typedef struct OB_STATE OB_STATE;

#define OB_Message_Type_USERMSG 0
#define OB_Message_Type_EVENT 1
union OB_Message_Arg{
	size_t ptrdiff;
	double number;
	int integer;
};
typedef union OB_Message_Arg OB_Message_Arg;
typedef struct OB_Message
{
	char* name;
	char* argType;
	OB_Message_Arg arg;
	int type;
	FSM_PTR sender;
	/** 是否共享，用于广播，获取参数时需要复制 */
	char share;
	uint8_t typeMask;
} OB_Message;

typedef struct OB_Message OB_Message;
typedef struct OB_Deque_Node OB_Deque_Node;
typedef struct OB_VM OB_VM;
typedef void (*OB_OBJ_destroy)(OB_VM* ,void* ,size_t );
void* __OB_malloc(OB_VM* vm, size_t size, char* typename,OB_OBJ_destroy destroy);
#define OB_malloc(vm,TYPE,READABLE_TYPE_NAME,destroy) __OB_malloc(vm,sizeof(TYPE),READABLE_TYPE_NAME,destroy)
void* GetOBNObj(OB_VM* vm, size_t ob_ptr);
size_t GetOBPtrByNative(OB_VM* vm, void* o);
size_t VMID(OB_VM* vm);
typedef union {
	size_t ob_ptr;
	int64_t i64;
	double f64;
}OB_List_Item;
typedef struct{
	unsigned int length;
	unsigned int capacity;
	char link;
    char readonly;
	size_t items_ptr;
}OB_List;
STR_PTR str2ptr(OB_VM* vm,char* str);
void OB_link_obj(OB_VM* vm, size_t from,size_t memberOffset, size_t target);
void OB_Message_destroy(OB_VM* vm , OB_Message* o,size_t ptr);
size_t OB_New_List(OB_VM* vm , char link,char* obtypename);
unsigned int OB_sizeOfMap(OB_VM* vm, size_t list_ptr);
void OB_Insert_Value_At_Index(OB_VM* vm, size_t list_ptr,size_t index,size_t ptr);
size_t OB_Get_Value_At_Index(OB_VM* vm, size_t list_ptr,size_t index);

#define GetNobjIntegerOrNumberField(type,fieldName,ptr) (((type *)(ptr))->fieldName)
#define GetNobjStringField(type,fieldName,ptr) (str2ptr(vm,(char*)((type *)(ptr))->fieldName))
int startRoarVM(void);
int updateRoarVM(void);

// 可选实现-异步支持
typedef struct AsyncOperation AsyncOperation;

typedef int (*AsyncOperationCallback)(AsyncOperation*);
typedef void (*callback)(void*);

struct AsyncOperation {
    OB_VM* vm;
    FSM_PTR fsm;
    AsyncOperationCallback func;
    void* userdata;
};
int runAsyncOperation(AsyncOperation* op);
int runInMainThread(void* data,callback func);

#endif
